package com.csist.servlet;

import com.csist.bean.Teacher;
import com.csist.dao.TeacherDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.List;

@WebServlet(name = "RegisterServlet", value = "/html/RegisterServlet")
@MultipartConfig
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("teacherName");
        boolean gender = "男".equals(request.getParameterValues("gender")[0]);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date bir = null;
        try {
            bir = new Date(format.parse(request.getParameter("teacherBirthday")).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String phone = request.getParameter("teacherBirthday");

        int state = Integer.parseInt(request.getParameterValues("teacherStatus")[0]);
        String dec = request.getParameter("teacherDesc");



        String username = request.getParameter("username");
        String userpass = request.getParameter("userpass");
        Teacher teacher = new Teacher(0,name,gender,bir,phone,state,dec,username,userpass);
        TeacherDao tDao = new TeacherDao();
        if (tDao.register(teacher)){
            //存储路径
            String savePath = request.getServletContext().getRealPath("/WEB-INF/uploadFile");
            Collection<Part> parts = request.getParts();//上传单个文件
            if (parts.size()==1) {
                //Servlet3.0将multipart/form-data的POST请求封装成Part，通过Part对上传的文件进行操作。
                //Part part = parts[0];//从上传的文件集合中获取Part对象
                Part part = request.getPart("file");//通过表单file控件(<input type="file" name="file">)的名字直接获取Part对象
                //Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
                //获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
                String header = part.getHeader("content-disposition");
                //获取文件名
                String fileName = getFileName(header);
                //把文件写到指定路径
                part.write(savePath+ File.separator+fileName);
            }else {
                //一次性上传多个文件
                for (Part part : parts) {//循环处理上传的文件
                    //获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
                    String header = part.getHeader("content-disposition");
                    //获取文件名
                    String fileName = getFileName(header);
                    //把文件写到指定路径
                    part.write(savePath+File.separator+fileName);
                }
            }
            response.getWriter().println("成功");
        } else {
            response.getWriter().println("失败");
        }
    }
    public String getFileName(String header) {
        /**
         * String[] tempArr1 = header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
         * 火狐或者google浏览器下：tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
         * IE浏览器下：tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
         */
        String[] tempArr1 = header.split(";");
        /**
         *火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
         *IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] tempArr2 = tempArr1[2].split("=");
        //获取文件名，兼容各种浏览器的写法
        String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"", "");
        return fileName;
    }
}
